package com.bullsora.kindlerss.business;


import com.bullsora.kindlerss.model.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;

import java.util.List;

public class AppUserServiceImpl implements AppUserService {

  @Autowired
  private PasswordEncoder passwordEncoder;

  public void saveAppUser(AppUser appUser) {
    encodeUserPassword(appUser);
    appUser.persist();
  }

  private void encodeUserPassword(AppUser appUser) {
    if (appUser.getInputPassword() != null) {
      appUser.setPassword(passwordEncoder.encodePassword(appUser.getInputPassword(), null));
    }
  }

  public AppUser updateAppUser(AppUser appUser) {
    encodeUserPassword(appUser);
    return appUser.merge();
  }

  @Override
  public AppUser findUserByEmail(String email) {
    List<AppUser> foundUsers = AppUser.findAppUsersByEmailEquals(email).getResultList();
    if (foundUsers != null && !foundUsers.isEmpty()) {
      return foundUsers.get(0);      
    }
    return null;
  }
}
